<?php
/** * IndexController is the default controller for this application */
class UsersController extends ControllerBase {
	/**	 * UsersDataService Object	 *	 * @var UsersDataService object	 */
	public $usersDataService = null;
	
	/**	 * CountryDataService Object	 *	 * @var CountryDataService object	 */
	public $countryDataService = null;
	
	/**	 * Constructor of users	 */
	public function __construct() {
		parent::__construct ();
		
		// Get status list of users		$this->smarty->assign ( 'statusList', UsersEntity::getStatusList () );
		
		$type = $this->getQuery ( 'type', "" );
		if (empty ( $type ) || intval ( $type ) == 0) {
			// Get status list of users			$this->smarty->assign ( 'userTypeList', UsersEntity::getMemberUserTypeList () );
			
			// Set page name			$this->setPageName ( 'user' );
		} else {
			// Get status list of users			$this->smarty->assign ( 'userTypeList', UsersEntity::getNormalAdminTypeList () );
			
			// Set page name			$this->setPageName ( 'settings' );
		}
		$this->smarty->assign ( 'type', $type );
		
		// New Users Data Service		$this->usersDataService = new UsersDataService ();
		
		// Init Country DataService		$this->countryDataService = new CountryDataService ();
		
		$this->smarty->assign ( 'listCountry', CommonDataService::getCountrylist () );
	
	}
	
	/**	 * The "index" action is the default action for all controllers -- the	 * landing page of the site. Return list of all users	 *	 * @access public	 *	 * @return void	 */
	public function indexAction() {
		// View users list		$this->listAction ();
	}
	
	/**	 * Dispplay List of users	 * landing page of the site. Return list of all users	 *	 * @access public	 *	 * @return void	 */
	public function listAction() {
		$arrElement = array ();
		$arrElement ["userType"] = ROLE_MEMBER;
		
		// Get all items of users		$itemList = $this->usersDataService->getItems ( $arrElement );
		
		$this->smarty->assign ( 'itemList', $itemList );
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Users/index.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**	 * Add action is trigger when admin want to add the users information	 *	 * @access public	 *	 * @return void	 */
	public function addAction() {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get action method and check it		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			
			// Get username field			$username = $this->getPost ( 'username', '' );
			
			// Get email field			$email = $this->getPost ( 'email', '' );
			
			// Get password field			$password = $this->getPost ( 'password', '' );
			// Encrypt password			$password = Authentication::encryptPassword ( $password );
			
			// Get firstName field			$firstName = $this->getPost ( 'firstName', '' );
			
			// Get lastName field			$lastName = $this->getPost ( 'lastName', '' );
			
			// Get country field			$countryId = $this->getPost ( 'countryId', '' );
			
			// Get city field			$city = $this->getPost ( 'city', '' );
			
			// Get hosue field			$house = $this->getPost ( 'house', '' );
			
			// Get address field			$address = $this->getPost ( 'address', '' );
			
			// Get zipcode field			$zipCode = $this->getPost ( 'zipCode', '' );
			
			// Get telephone field			$telephone = $this->getPost ( 'telephone', '' );
			
			// Get userType field			$userType = $this->getPost ( 'userType', '' );
			
			// Get status field			$status = $this->getPost ( 'status', '' );
			
			/*			 * Validate some fields on server			 */
			// [Add code here...]			try {
				// Save data into database				$usersEntity = $this->usersDataService->beforeCreate ();
				$usersEntity->username = $username;
				$usersEntity->email = $email;
				$usersEntity->password = $password;
				$usersEntity->firstName = $firstName;
				$usersEntity->lastName = $lastName;
				$usersEntity->countryId = $countryId;
				$usersEntity->city = $city;
				$usersEntity->house = $house;
				$usersEntity->address = $address;
				$usersEntity->zipCode = $zipCode;
				$usersEntity->telephone = $telephone;
				$usersEntity->userType = $userType;
				$usersEntity->status = $status;
				$usersEntity->hasVerified = 1;
				$usersEntity->activationCode = md5 ( $username . "vinatay" );
				$res = $this->usersDataService->create ( $usersEntity );
				
				// Show a message				$resultMessage = 'The record has been created successfully';
			} catch ( Exception $ex ) {
				// Ignore to process this case. Only show a message				$resultMessage = 'The record cannot create successfully';
			}
		}
		
		// Create new token key		$_SESSION ['tokenKey'] = sha1 ( CommonUtils::randomNumber ( 10 ) );
		$this->smarty->assign ( 'resultMessage', isset ( $resultMessage ) ? $resultMessage : '' );
		$this->smarty->assign ( 'actionKey', $_SESSION ['tokenKey'] );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Users/add.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**	 * Edit action is trigger when admin want to edit the users information	 *	 * @access public	 *	 * @return void	 */
	public function editAction() {
		// Error flag		$isError = false;
		
		// Get id of users		$id = $this->getPost ( 'id', '' );
		if (is_null ( $id ) || $id == '') {
			$id = $this->getQuery ( 'id', '' );
		}
		// If the id of users does not exist, go on to view list page		if (empty ( $id )) {
			$this->listAction ();
			return - 1;
		}
		
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get action method and check it		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit' && (! isset ( $_SESSION ['tokenKey'] ) || $actionKey == $_SESSION ['tokenKey'])) {
			
			// Get username field			$username = $this->getPost ( 'username', '' );
			
			// Get email field			$email = $this->getPost ( 'email', '' );
			
			// Get title field			$title = $this->getPost ( 'title', '' );
			
			// Get firstName field			$firstName = $this->getPost ( 'firstName', '' );
			
			// Get lastName field			$lastName = $this->getPost ( 'lastName', '' );
			
			// Get country field			$country = $this->getPost ( 'country', '' );
			
			// Get city field			$city = $this->getPost ( 'city', '' );
			
			// Get address field			$house = $this->getPost ( 'house', '' );
			
			// Get telephone field			$telephone = $this->getPost ( 'telephone', '' );
			
			// Get userType field			$userType = $this->getPost ( 'userType', '' );
			
			// Get status field			$status = $this->getPost ( 'status', '' );
			
			// [Add code here...]			try {
				// Save data into database				$usersEntity = $this->usersDataService->beforeUpdate ( $id );
				if (is_null ( $usersEntity )) {
					throw new Exception ( 'The id of users does not exist', 1 );
				}
				$usersEntity->id = $id;
				$usersEntity->username = $username;
				$usersEntity->email = $email;
				//$usersEntity->password = $password;				$usersEntity->firstName = $firstName;
				$usersEntity->lastName = $lastName;
				$usersEntity->countryId = $country;
				$usersEntity->city = $city;
				$usersEntity->house = $house;
				$usersEntity->telephone = $telephone;
				$usersEntity->userType = $userType;
				$usersEntity->status = $status;
				$res = $this->usersDataService->update ( $usersEntity );
				
				// Show a message				$resultMessage = 'The record has been updated successfully';
			} catch ( Exception $ex ) {
				echo $ex->getMessage ();
				// Ignore to process this case. Only show a message				$resultMessage = 'The record cannot update successfully';
				$isError = true;
			}
		}
		
		// View data		$usersEntityDetail = $this->usersDataService->getById ( $id );
		
		// If the id of users not exist, go on to view list page		if (is_null ( $usersEntityDetail ) || is_null ( $usersEntityDetail )) {
			$this->listAction ();
			return - 1;
		}
		
		// Create new token key		$_SESSION ['tokenKey'] = sha1 ( CommonUtils::randomNumber ( 10 ) );
		$this->smarty->assign ( 'resultMessage', isset ( $resultMessage ) ? $resultMessage : '' );
		$this->smarty->assign ( 'actionKey', $_SESSION ['tokenKey'] );
		$this->smarty->assign ( 'id', ($isError == true) ? $id : $usersEntityDetail->id );
		$this->smarty->assign ( 'username', ($isError == true) ? $username : $usersEntityDetail->username );
		$this->smarty->assign ( 'email', ($isError == true) ? $email : $usersEntityDetail->email );
		//$this->smarty->assign('password', ($isError == true) ? $password : $usersEntityDetail->password);		$this->smarty->assign ( 'firstName', ($isError == true) ? $firstName : $usersEntityDetail->firstName );
		$this->smarty->assign ( 'lastName', ($isError == true) ? $lastName : $usersEntityDetail->lastName );
		$this->smarty->assign ( 'countryId', ($isError == true) ? $country : $usersEntityDetail->countryId );
		$this->smarty->assign ( 'city', ($isError == true) ? $city : $usersEntityDetail->city );
		$this->smarty->assign ( 'house', ($isError == true) ? $address : $usersEntityDetail->house );
		$this->smarty->assign ( 'telephone', ($isError == true) ? $telephone : $usersEntityDetail->telephone );
		$this->smarty->assign ( 'userType', ($isError == true) ? $userType : $usersEntityDetail->userType );
		$this->smarty->assign ( 'lastVisit', ($isError == true) ? $lastVisit : $usersEntityDetail->lastVisit );
		$this->smarty->assign ( 'status', ($isError == true) ? $status : $usersEntityDetail->status );
		$this->smarty->assign ( 'createdDate', ($isError == true) ? $createdDate : $usersEntityDetail->createdDate );
		$this->smarty->assign ( 'modifiedDate', ($isError == true) ? $modifiedDate : $usersEntityDetail->modifiedDate );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Users/edit.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**	 * Active some records of users	 *	 * @access public	 *	 * @return void	 */
	public function activeAction() {
		$this->updateStatus ( UsersEntity::ACTIVE );
		
		// View users list		$this->listAction ();
	}
	
	/**	 * Inactive some records of users	 *	 * @access public	 *	 * @return void	 */
	public function inactiveAction() {
		$this->updateStatus ( UsersEntity::INACTIVE );
		
		// View users list		$this->listAction ();
	}
	
	/**	 * Delete action is trigger when administrator want to delete a users	 *	 * @access public	 *	 * @return void	 */
	public function deleteAction() {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		//if (!isset($_SESSION['tokenKey']) || $actionKey == $_SESSION['tokenKey']){		// Get Id of users		$id = $this->getPost ( 'idValue', '' );
		
		// Delete a users item		$res = $this->usersDataService->del ( $id );
		//}		

		// View users list		$this->listAction ();
	}
	
	/**	 * Delete list of users	 *	 * @access public	 *	 * @return void	 */
	public function deleteallAction() {
		$iCount = $this->getPost ( 'iCount', 0 );
		for($i = 0; $i < $iCount; $i ++) {
			$id = $this->getPost ( 'checkItem' . $i, '' );
			if (! empty ( $id )) {
				
				// Delete a users item				$this->usersDataService->del ( $id );
			}
		}
		
		// View users list		$this->listAction ();
	}
	
	/**	 * Update status list of users	 *	 * @access private	 *	 * @param int $status: Status of the users	 *	 * @return void	 */
	protected function updateStatus($status) {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		if (! isset ( $_SESSION ['tokenKey'] ) || $actionKey == $_SESSION ['tokenKey']) {
			$iCount = $this->getPost ( 'iCount', 0 );
			for($i = 0; $i < $iCount; $i ++) {
				$id = $this->getPost ( 'checkItem' . $i, '' );
				if (! empty ( $id )) {
					$this->usersDataService->updateStatus ( $id, $status );
				}
			}
		}
	}
	
	/**	 * Get User Name od a Userid	 *	 * @access public	 *	 * @param int $userId: User ID	 *	 * @return string	 */
	public function getCountryName($countryId) {
		$str = "";
		if ($countryId != "") {
			$item = $this->countryDataService->getById ( $countryId );
			if (isset ( $item )) {
				$str = $item->name;
			}
		}
		
		return $str;
	}
	
	/**	 * Logout Admin	 *	 * @return None	 */
	public function logoutAction() {
		// Save urer history which he is visiting		//$this->userSessionVisitDataService->saveHistoryForCurrentUser(USER_VISIT_ADMIN_LOGOUT);		

		// Logout		$this->usersDataService->logout ();
		
		// Redirect to homepage		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Login/index';
		CommonUtils::redirect ( $url );
	}
	
	/**	 * Resend Password action is trigger when administrator want to resend pass to a user	 *	 * @access public	 *	 * @return void	 */
	public function resendPassAction() {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get Id of users		$id = $this->getPost ( 'idValue', '' );
		if ($id != "") {
			//Resend Password to user			$res = $this->usersDataService->resendPassword ( $id );
		}
		
		// View users list		$this->listAction ();
	}
	
	/**	 * Resend Password action is trigger when administrator want to resend pass to a user	 *	 * @access public	 *	 * @return void	 */
	public function resendActCodeAction() {
		// Get action key		$actionKey = $this->getPost ( 'actionKey', '' );
		
		// Get Id of users		$id = $this->getPost ( 'idValue', '' );
		if ($id != "") {
			
			//Resend Password to user			$res = $this->usersDataService->resendActivationCode ( $id );
		}
		
		// View users list		$this->listAction ();
	}
	
	/*	 *	Latest purchased products of Users	 */
	public function purchasedAction() {
		// Get id of users		$id = $this->getPost ( 'id', '' );
		if (is_null ( $id ) || $id == '') {
			$id = $this->getQuery ( 'id', '' );
		}
		// If the id of users does not exist, go on to view list page		if (empty ( $id )) {
			$this->listAction ();
			return - 1;
		}
		
		// Geting all latest purchase products		$arrElement = array ();
		$arrElement ['userId'] = $id;
		$productOrderDataService = new ProductOrderDataService ();
		
		$arrLatestPurchasedProductEntity = $productOrderDataService->getItems ( $arrElement, 'createdDate DESC', NULL, NULL );
		
		$this->smarty->assign ( 'itemList', $arrLatestPurchasedProductEntity );
		$this->smarty->assign ( 'this', $this );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Users/purchased.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**	 * Get Product Name of a product	 *	 * @access public	 *	 * @param int $productId: Product ID	 *	 * @return string	 */
	public function getProductName($productId) {
		$productDatdaService = new ProductDataService ();
		$str = "";
		if ($productId != "") {
			
			$item = $productDatdaService->getById ( $productId );
			if (isset ( $item )) {
				$str = $item->name;
			}
		}
		
		return $str;
	}
	
	/**	 * Get Option Price of a product	 *	 * @access public	 *	 * @param int $productId: Product ID	 *	 * @return string	 */
	public function getOptionName($productOptionDetailsId) {
		
		$productOptionDetailsDataService = new ProductOptionDetailDataService ();
		$productOptionDataService = new ProductOptionsDataService ();
		
		$str = "";
		if ($productOptionDetailsId != "") {
			$detailsItem = $productOptionDetailsDataService->getById ( $productOptionDetailsId );
			if (isset ( $detailsItem )) {
				$item = $productOptionDataService->getById ( $detailsItem->productOptionId );
				
				if (isset ( $item )) {
					$str = $item->name;
				}
			}
		}
		
		return $str;
	}
	
	/**	 * Change Admin password action	 *	 * @return void	 */
	public function changePasswordAction() {
		$isError = false;
		$error = "";
		
		// Set page name		$this->setPageName ( 'admin_user_change_pass' );
		$authenticate = new Authentication ();
		
		$usersEntity = $this->usersDataService->getById ( $authenticate->getCurrentUserId () );
		$this->smarty->assign ( 'usersEntity', $usersEntity );
		
		$actionForm = $this->getPost ( 'actionForm', '' );
		if (! empty ( $actionForm ) && $actionForm == 'submit') {
			
			$oldPass = $this->getPost ( 'currentPassword', '' );
			$newPass = $this->getPost ( 'newPassword', '' );
			$oldPassEn = $authenticate->encryptPassword ( $oldPass );
			$newPassEn = $authenticate->encryptPassword ( $newPass );
			
			if ($oldPassEn == $usersEntity->password) {
				$usersEntity = $this->usersDataService->beforeUpdate ( $authenticate->getCurrentUserId () );
				$usersEntity->password = $newPassEn;
				$res = $this->usersDataService->update ( $usersEntity );
				
				$error = "Password is changed succesfully!";
			} else {
				$isError = true;
				// Ignore to process this case. Only show a message				$error = 'The password is not correct. Please try again!';
			}
		}
		
		// Set page name		$this->setPageName ( 'settings' );
		
		$this->smarty->assign ( 'error', isset ( $error ) ? $error : '' );
		$this->smarty->assign ( 'isError', isset ( $isError ) ? $isError : false );
		$this->smarty->assign ( 'SMARTY_CONTENT_PATH', 'Admin/Users/changepassword.tpl' );
		$this->smarty->display ( APPLICATION_PATH . '/Layouts/Admin/MainLayout.tpl' );
	}
	
	/**	 * Login To User's Panel	 */
	public function loginUserAction() {
		// Get id of users		$id = $this->getPost ( 'idValue', '' );
		if (empty ( $id ) || ! is_numeric ( $id )) {
			// Redirect to User List Page			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Users';
			CommonUtils::redirect ( $url );
		}
		
		$usersDataService = new UsersDataService ();
		$result = $usersDataService->loginUser ( $id );
		if ($result == SUCC) {
			$this->loginsuccessAction ();
		} else {
			$isError = true;
			$this->smarty->assign ( 'isError', $isError );
			$this->smarty->assign ( 'errorLoginMessage', 'Sorry, but we could not find login details using the information you supplied. Please try again!' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
		}
	
	}
	
	/**	 * Action when user login successfully	 *	 * @return next action	 */
	private function loginsuccessAction() {
		$authentication = new Authentication ();
		
		if ($authentication->isMember () == true) {
			if (isset ( $_SESSION ['urlCallBack'] ) && ! is_null ( $_SESSION ['urlCallBack'] )) {
				$url = $_SESSION ['urlCallBack'];
				unset ( $_SESSION ['urlCallBack'] );
				CommonUtils::redirect ( $url );
				return - 1;
			}
			
			$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/MyAccount';
			CommonUtils::redirect ( $url );
			return - 1;
		} else {
			
			$this->smarty->assign ( 'errorLoginMessage', 'Sorry, Only Customer can access. Please try again!' );
			$this->smarty->display ( APPLICATION_PATH . '/Layouts/Browse/MainLayout.tpl' );
		}
	
	}
}